package com.sdkx.app.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;

import com.sdkx.app.R;
import com.sdkx.app.util.Util;

public class DegreeInputView extends android.support.v7.widget.AppCompatEditText {
    private final static String TAG = DegreeInputView.class.getSimpleName();
    Handler handler = new Handler();
    private boolean global_line = true;

    public DegreeInputView(Context context) {
        super(context);
        init(null);
    }

    public DegreeInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DegreeInputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        String backInfo;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            backInfo = s.toString();
            Log.d(TAG, "before change: " + s.toString());

        }

        @Override
        public void onTextChanged(final CharSequence s, int start, int before, int count) {
            Log.d(TAG, "onTextChanged: " + s.toString());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    String oldinfo = s.toString();
                    String sinfo = getString(s.toString());
                    if (checkWordsIlligal(sinfo)) {
                        sinfo = backInfo;
                    }

                    if (!oldinfo.equals(sinfo)) {
                        removeTextChangedListener(mTextWatcher);

                        setText(sinfo);
                        setSelection(sinfo.length());
                        addTextChangedListener(mTextWatcher);
                    }


                }
            });

        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d(TAG, "afterTextChanged: " + s.toString());
        }

        private boolean checkWordsIlligal(String info) {
            int[] section = new int[3];
            section[0] = info.lastIndexOf("°");
            section[1] = info.lastIndexOf('′');
            section[2] = info.lastIndexOf('″');
            int length = info.length();
            if (length <= 1) return false;
            if (section[0] > 0)
                length = section[0];

            String degree = info.substring(1, length);

            int macdegree = 180;
            if (!global_line)
                macdegree = 90;
            if (!checkDegree(degree, macdegree)) {
                return true;
            }
            if (section[0] > 0 && section[0] < (info.length()-1) && degree.contains(".")) {

                return true;
            }
            if (section[0] < 0)
                return false;
            length = info.length();
            if (section[1] > 0)
                length = section[1];
            degree = info.substring(section[0] + 1, length);
            if (TextUtils.isEmpty(degree))
                return false;
            if (!checkDegree(degree, 60)) {
                return true;
            }
            if (section[1]> 0 && section[1] < (info.length()-1)  && degree.contains(".")) {
                return true;
            }

            if (section[1] < 0)
                return false;
            length = info.length();

            if (section[2] > 0)
                length = section[2];
            degree = info.substring(section[1] + 1, length);
            if (TextUtils.isEmpty(degree))
                return false;
            if (!checkDegree(degree, 60)) {
                return true;
            }
            if (section[2] < 0)
                return false;


            return false;
        }

        private boolean checkDegree(String info, int maxdegree) {
            double idegree = 0.0f;
            try {
                idegree = Double.valueOf(info).doubleValue();
            } catch (NumberFormatException e) {
                e.printStackTrace();
                return false;
            }
            if (idegree < 0 || idegree - maxdegree > 0.0000001)
                return false;

            return true;
        }

        private String getString(String input) {
            if (input == null || input.length() == 0)
                return "";

            if (input.length() > 6 && input.charAt(input.length() - 2) == '″') {
                int min = input.substring(0, input.length() - 3).indexOf("″");
                if (min > 0 && min < input.length()) {
                    return input.substring(0, input.length() - 1);
                }
            }

            String info = "";
            int selection = getSelectionStart();
            {
                if (backInfo.length() < input.length()) {
                    char cin = input.charAt(selection - 1);
                    switch (cin) {
                        case '+': {
                            StringBuilder builder = new StringBuilder();
                            if (global_line)
                                builder.append("E");
                            else {
                                builder.append("N");
                            }
                            if (backInfo.length() > 1) {
                                builder.append(backInfo.substring(1, backInfo.length()));
                            }
                            return builder.toString();
                        }
                        case '-': {
                            StringBuilder builder = new StringBuilder();
                            if (global_line)
                                builder.append("W");
                            else
                                builder.append("S");
                            if (backInfo.length() > 1) {
                                builder.append(backInfo.substring(1, backInfo.length()));
                            }
                            return builder.toString();
                        }
                    }
                    if (!((cin == '.') || cin == ' ' || (cin <= '9' && cin >= '0') || cin == '′' || cin == '″' || cin == '°')) {
                        return backInfo;
                    } else {

                        if ((cin == '.')) {
                            if (backInfo.length() == 0) return backInfo;
                            char ll = input.charAt(selection - 2);
                            if (!(ll <= '9' && ll >= '0'))
                                return backInfo;
                        } else if (cin == ' ') {
                            int length = backInfo.length();
                            if (backInfo.length() == 0 || selection <= length)
                                return backInfo;
                            char ll = backInfo.charAt(backInfo.length() - 1);
                            if (!(ll <= '9' && ll >= '0'))
                                return getUperSection(backInfo, "00");
                            else
                                return getUperSection(backInfo, "");
                        } else {
                            if (backInfo.length() == 0) {
                                String temp = "E" + input;
                                if (!global_line)
                                    temp = "N" + input;
                                return temp;
                            }
                            if (selection > backInfo.length()) {
                                int dpos = input.lastIndexOf('″');
                                if (dpos > 0)
                                    return backInfo;
                            }
                        }

                    }
                }

                if (backInfo.length() < input.length() || selection == input.length()) {
                    info = input;

                } else {
                    try {
                        if (selection + 1 == backInfo.length()) {
                            return backInfo;
                        }
                        char behand = backInfo.charAt(selection + 1);
                        char frontn1 = backInfo.charAt(selection);
                        boolean bfront = false;
                        boolean bbehind = false;
                        boolean bfrontn1 = false;

                        if (selection > 0) {
                            char front = backInfo.charAt(selection - 1);
                            switch (front) {
                                case '′':
                                    // case '″':
                                case '°':
                                case 'W':
                                case 'E':
                                case 'N':
                                case 'S':
                                    bfront = true;
                                    break;
                            }
                        }
                        switch (behand) {
                            case '′':
                            case '″':
                            case '°':
                                bbehind = true;
                                break;

                        }

                        switch (frontn1) {
                            case '°':
                            case '′':
                            case 'W':
                            case 'E':
                            case 'N':
                            case 'S':
                                bfrontn1 = true;
                                break;
                        }

                        if (bfront && bbehind) {
                            StringBuilder builder = new StringBuilder();
                            builder.append(input.substring(0, selection));
                            builder.append("00");
                            builder.append(input.substring(selection, input.length()));
                            info = builder.toString();
                        } else if (bfrontn1) {
                            info = backInfo;
                        } else
                            info = input;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //   }

            return info;
        }

        private String getUperSection(String input, String zero) {
            int[] section = new int[3];
            String result = "";
            section[0] = input.lastIndexOf("°");
            section[1] = input.lastIndexOf('′');
            section[2] = input.lastIndexOf('″');
            int sec = 0;
            int max = section[0];
            for (int index = 1; index < section.length; index++) {
                if (max < section[index]) {
                    max = section[index];
                    sec = index;
                }
            }
            if (max < 0) {
                result = input + "°";
            } else {
                switch (sec) {
                    case 0:
                        result = input + zero + "′";
                        break;
                    case 1:
                        result = input + zero + "″";
                        break;
                    case 2:
                        result = input;
                        break;
                }
            }
            return result;
        }
    };

    public void init(AttributeSet attrs) {
        if (null != attrs) {
            TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DegreeInputView);
            String linetype = ta.getString(R.styleable.DegreeInputView_globosity_line);
            if ("1".equals(linetype)) {
                global_line = true;
                setHint("空格为°\\′\\″，+\\-号为东\\西经 ");
            } else {
                global_line = false;
                setHint("空格为°\\′\\″，+\\-号为北\\南纬 ");

            }
            setHintTextColor(Color.parseColor("#AAAAAA"));
            ta.recycle();
        }

        this.addTextChangedListener(mTextWatcher);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacksAndMessages(null);
    }

    public boolean checkillegal() {
        boolean flag = false;
        String info = getText().toString();

        if (!TextUtils.isEmpty(info)) {
            int degree = info.indexOf('°', 0);
            int secPart = info.indexOf('′', degree);
            int thirdPart = info.indexOf('″', secPart);
            if (degree < 0) {
                flag = true;
            } else {
                boolean condition1 = secPart < 0 && info.length() > (degree+1) && thirdPart < 0;
                boolean condition2 = secPart > 0 && info.length() > (secPart+1) && thirdPart < 0;
                if (condition1 || condition2) {
                    flag = true;
                }
            }
        }
        return flag;
    }
    //
//        int degree = info.indexOf('°', 1);
//        int part1 = info.indexOf('′', degree);
//        int part2 = info.indexOf('″', part1);
//        String sdegree = "";
//        String sfen = "";
//        String miao = "";
//        if (degree >= 0)
//            sdegree = info.substring(1, degree);
//
//        if (part1 >= 0) {
//            if (degree < 0)
//                degree = 0;
//            sfen = info.substring(degree + 1, part1);
//        }
//
//        if (part2 > 0) {
//            int precount = part1;
//            if (precount < 0)
//                precount = degree;
//            if (precount < 0)
//                precount = 0;
//            miao = info.substring(precount + 1, part2);
//        }
//        StringBuilder builder = new StringBuilder();
//        builder.append(info.charAt(0));
//        if (sdegree.contains(".")) {
//            double alldata = Double.valueOf(sdegree);
//            builder.append((int) alldata);
//            double afendata = (alldata - ((int) alldata)) * 60;
//            if(((int) afendata) < 10)
//                builder.append("0");
//            builder.append((int) afendata);
//            double isec = (afendata - ((int) afendata)) * 60;
//            if(((int)isec)<10)
//                builder.append("0");
//            builder.append(String.format("%.2f",isec));
//            return builder.toString();
//        } else {
//            if (!TextUtils.isEmpty(sdegree)) {
//                builder.append(sdegree);
//            } else {
//                builder.append("00");
//            }
//        }
//        if (sfen.contains(".")) {
//            double fendata = Double.valueOf(sfen);
//            if(((int)fendata) < 10 )
//                builder.append("0");
//            builder.append((int) fendata);
//            double sec = (fendata - ((int) fendata)) * 60;
//            if(((int)sec)<10)
//                builder.append("0");
//            builder.append(String.format("%.2f",sec));
//            return builder.toString();
//        } else {
//            if (!TextUtils.isEmpty(sfen)) {
//                if(sfen.length()<2)
//                    builder.append("0");
//                builder.append(sfen);
//            } else {
//                builder.append("00");
//            }
//        }
//        if (!TextUtils.isEmpty(miao)) {
//            double dmiao = Double.valueOf(miao);
//            if(((int)dmiao) < 10)
//                builder.append("0");
//            builder.append(String.format("%.2f",dmiao));
//        } else {
//            builder.append("00.00");
//        }
    public String toDegree() {
        return Util.toStardardDegree(getText().toString());
    }

    public void setTextEx(String text) {
        removeTextChangedListener(mTextWatcher);
        setText(text);
        addTextChangedListener(mTextWatcher);
    }


}
